package org.red_cross_service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.red_cross_service.domain.dto.TrainingInfo;
import org.red_cross_service.domain.entity.ActivityEntity;
import org.red_cross_service.domain.entity.LearnRecordEntity;
import org.red_cross_service.domain.entity.VideoEntity;
import org.red_cross_service.mapper.LearnRecordMapper;
import org.red_cross_service.mapper.VideoMapper;
import org.red_cross_service.utils.EasyExcelUtils;
import org.red_cross_service.utils.QueryWrapperUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.red_cross_service.common.response.Response;
import org.red_cross_service.domain.vo.AvtivityVO;
import org.red_cross_service.mapper.ActivityMapper;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ActivityService {

    @Autowired
    ActivityMapper activityMapper;

    @Autowired
    LearnRecordMapper learnRecordMapper;

    @Autowired
    private VideoMapper videoMapper;

    /**
     * @param type   0进行中 1已结束
     * @param userId 用户id
     *               <p>
     *               return
     *               isFinish 0 去学习 1 已完成 2 未完成 3 已结束
     */
    public Response getAllActivity(Integer type, Integer userId) {
        List<AvtivityVO> list;
        if (type == 0) list = activityMapper.getUserActivities(userId);
        else if (type == 1) list = activityMapper.getUserPassActivities(userId);
        else return Response.error("未知Type");

        List<LearnRecordEntity> recordEntityList = learnRecordMapper.selectList(
                new QueryWrapper<LearnRecordEntity>().eq("user_id", userId)
        );
        Map<Long, LearnRecordEntity>    statusMap = recordEntityList
                    .stream().collect(Collectors.toMap(LearnRecordEntity::getActivityId, o -> o));
        for (AvtivityVO avtivityVO : list) {
            LearnRecordEntity learnRecordEntity = statusMap.getOrDefault(avtivityVO.getActivityId(), null);
            if (learnRecordEntity == null) {
                avtivityVO.setUserProcess(0);
                avtivityVO.setVideosStatus(0);
                avtivityVO.setIsFinish(type == 0 ? 0 : 3);
                continue;
            } else {
                BeanUtils.copyProperties(learnRecordEntity, avtivityVO);
            }

            try {
                ObjectMapper mapper = new ObjectMapper();
                int[] ints = mapper.readValue(avtivityVO.getVideosProcess(), int[].class);
                int sum = Arrays.stream(ints).sum();
                if (type == 0) {
                    if (sum < avtivityVO.getVideosLength().doubleValue()) {
                        avtivityVO.setIsFinish(0);
                    } else {
                        avtivityVO.setIsFinish(1);
                    }
                } else {
                    if (sum < avtivityVO.getVideosLength().doubleValue()) {
                        avtivityVO.setIsFinish(2);
                    } else {
                        avtivityVO.setIsFinish(1);
                    }
                }
                avtivityVO.setUserProcess(sum);
            } catch (JsonProcessingException e) {
                return Response.error(e.getMessage());
            }
        }
        return Response.success("查询成功！", list);
    }

    public Response getActivityOne(Integer activityId, Integer userId) {
        AvtivityVO avtivityVO = activityMapper.getUserOneActivity(activityId, userId);
        return Response.success("查询成功！", avtivityVO);
    }

    public Response getActivityList(ActivityEntity activityEntity) {
        return Response.success("查询成功！",
                activityMapper.selectList(
                        QueryWrapperUtils.buildQuery(
                                activityEntity
                        )
                )
        );
    }

    public Response add(ActivityEntity activityEntity) {
        //统计视频表所有视频的视频长度总和
        List<VideoEntity> videoEntities = videoMapper.selectList(new QueryWrapper<>());
        //videoEntities转json字符串
        if(!videoEntities.isEmpty()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                TrainingInfo[] trainingInfos = objectMapper.readValue(activityEntity.getTrainingInfo(), TrainingInfo[].class);
                for (TrainingInfo trainingInfo : trainingInfos) {
                    String startDateString = trainingInfo.getStartDate();
                    String endDateString = trainingInfo.getEndDate();
                    //培训时间 样例格式 2023-03-07日 08:00-09:00 因为开始时间和结束时间是一天
                    String dateString = startDateString.substring(0, 10);
                    String endDateStringSub = endDateString.substring(0, 10);
                    trainingInfo.setDate(MessageFormat.format("{0}日-{1}日", dateString, endDateStringSub));

                    //转回json字符串
                    activityEntity.setTrainingInfo(objectMapper.writeValueAsString(trainingInfos));
                }
                activityEntity.setVideosInfo(new ObjectMapper().writeValueAsString(videoEntities));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            Long allLength = videoMapper.sumLength();
            activityEntity.setVideosLength(new BigDecimal(allLength));
        }
        return Response.success("添加成功！", activityMapper.insert(activityEntity));
    }

    @SneakyThrows
    public Response update(ActivityEntity activityEntity) {

        ObjectMapper objectMapper = new ObjectMapper();
        TrainingInfo[] trainingInfos = objectMapper.readValue(activityEntity.getTrainingInfo(), TrainingInfo[].class);
        for (TrainingInfo trainingInfo : trainingInfos) {
            String startDateString = trainingInfo.getStartDate();
            String endDateString = trainingInfo.getEndDate();
            //培训时间 样例格式 2023-03-07日 08:00-09:00 因为开始时间和结束时间是一天
            String dateString = startDateString.substring(0, 10);
            String endDateStringSub = endDateString.substring(0, 10);
            trainingInfo.setDate(MessageFormat.format("{0}日-{1}日", dateString, endDateStringSub));//转回json字符串
            activityEntity.setTrainingInfo(objectMapper.writeValueAsString(trainingInfos));
        }
        return Response.success("修改成功！", activityMapper.updateById(activityEntity));
    }


    public Response delete(Integer activityId) {
        return Response.success("删除成功！", activityMapper.deleteById(activityId));
    }

    public Response selectOne(ActivityEntity activityEntity) {
        return Response.success("查询成功！", activityMapper.selectOne(
                QueryWrapperUtils.buildQuery(activityEntity)
        ));
    }

    public void exportActivity(HttpServletResponse response, ActivityEntity activityEntity) {
        try {
            List<ActivityEntity> activityEntityList = activityMapper.selectList(
                    QueryWrapperUtils.buildQuery(
                            activityEntity
                    )
            );
            EasyExcelUtils.writeWeb(response, activityEntityList, ActivityEntity.class, "活动列表", "活动列表");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
